<template>
  <div class="video-container">
    <div class="video-wrapper">
      <video
        v-if="videoUrl"
        controls
        class="video-player"
        disablePictureInPicture
        @timeupdate="handleTimeUpdate"
        @loadedmetadata="handleVideoLoaded"
        ref="videoRef"
      >
        <source :src="videoUrl" type="video/mp4" />
        您的浏览器不支持视频播放。
      </video>
      <div class="video-controls">
        <el-button 
          type="primary" 
          @click="handleReplay" 
          class="replay-button"
          :icon="Refresh"
          round
        >
          重新播放
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { Refresh } from "@element-plus/icons-vue";

const route = useRoute();
const videoUrl = ref("");
const videoRef = ref(null);
let lastCurrentTime = 0;
const isInitialSeek = ref(true);

// 保存播放进度
const saveVideoProgress = (currentTime) => {
  const fileName = route.query.url;
  if (fileName) {
    const progress = currentTime / videoRef.value.duration;
    localStorage.setItem(
      `video-progress-${fileName}-${route.query.id}`,
      progress
    );
    // 发送自定义事件通知进度更新
    window.dispatchEvent(
      new CustomEvent("video-progress-update", {
        detail: {
          fileName,
          progress,
        },
      })
    );
  }
};

// 获取保存的播放进度
const getVideoProgress = (fileName) =>
  parseFloat(
    localStorage.getItem(`video-progress-${fileName}-${route.query.id}`)
  ) || 0;

const handleTimeUpdate = (event) => {
  const video = event.target;
  if (isInitialSeek.value) {
    lastCurrentTime = video.currentTime;
    isInitialSeek.value = false;
    return;
  }

  if (Math.abs(video.currentTime - lastCurrentTime) > 1) {
    video.currentTime = lastCurrentTime;
  } else {
    lastCurrentTime = video.currentTime;
    saveVideoProgress(video.currentTime);
  }
};

// 视频加载完成后设置上次播放位置
const handleVideoLoaded = () => {
  if (videoRef.value) {
    const fileName = route.query.url;
    const savedTime = getVideoProgress(fileName);
    if (savedTime) {
      isInitialSeek.value = true;
      videoRef.value.currentTime = savedTime * videoRef.value.duration;
    }
  }
};

const clearAllVideoProgress = (fileName) => {
  // 清除特定视频的进度
  localStorage.removeItem(`video-progress-${fileName}-${route.query.id}`);
  
  // 清除可能存在的其他相关存储
  const keys = Object.keys(localStorage);
  const videoProgressKeys = keys.filter(key => 
    key.startsWith('video-progress-') && 
    key.includes(fileName)
  );
  
  videoProgressKeys.forEach(key => {
    localStorage.removeItem(key);
  });
};

const handleReplay = () => {
  const fileName = route.query.url;
  if (fileName) {
    // 重置所有状态
    isInitialSeek.value = true;
    lastCurrentTime = 0;
    
    // 清除所有相关的视频进度
    clearAllVideoProgress(fileName);
    
    // 重置视频到开始位置并播放
    if (videoRef.value) {
      videoRef.value.currentTime = 0;
      videoRef.value.pause(); // 先暂停
      setTimeout(() => {
        videoRef.value.play(); // 确保状态重置后再播放
      }, 0);
    }
    
    // 发送自定义事件通知进度更新
    window.dispatchEvent(
      new CustomEvent("video-progress-update", {
        detail: {
          fileName,
          progress: 0,
        },
      })
    );
  }
};

onMounted(() => {
  const url = route.query.url;
  const name = route.query.name;
  if (url && name) {
    videoUrl.value = url;
    document.title = name;
  }
});
</script>

<style scoped>
.video-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  padding: 20px;
}

.video-wrapper {
  width: 100%;
  max-width: 1200px;
  position: relative;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.video-player {
  width: 100%;
  height: calc(100vh - 200px);
  border-radius: 4px;
  background-color: black;
}

.video-controls {
  position: absolute;
  top: 30px;
  right: 30px;
  z-index: 10;
}

.replay-button {
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.replay-button:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
</style>
